package com.yiyingcanfeng.ping;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.yiyingcanfeng.ping.util.AlertDialogUtil;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Timer;
import java.util.TimerTask;


public class MainActivity extends AppCompatActivity implements View.OnClickListener {


    private EditText et_host;
    private EditText et_count;
    private EditText et_timeout;
    private Button btn_ping;
    private EditText tv_msg;
    private Button btn_help;
    private EditText et_interval;
    private Button mBtnStop;

    private Thread thread;
    private boolean flag = true;
    Process p;
    BufferedReader in = null;
    BufferedReader error = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();

    }

    Runnable runnable = new Runnable() {

        @Override
        public void run() {
            String ipAddress = "114.114.114.114";
            String count = "2";
            String timeOut = "2000";
            String interval = "1";
            if (!et_host.getText().toString().equals("")) {
                ipAddress = et_host.getText().toString();
            }
            if (!et_count.getText().toString().equals("")) {
                count = et_count.getText().toString();
            }
            if (!et_timeout.getText().toString().equals("")) {
                timeOut = et_timeout.getText().toString();
            }
            if (!et_interval.getText().toString().equals("")) {
                interval = et_interval.getText().toString();
            }



            String pingCommand = "ping -c " + count + " -W " + timeOut + " " + " -i " + interval + " " + ipAddress;
            Log.e("pingCommand", pingCommand);
            try {
                p = Runtime.getRuntime().exec(pingCommand);
                in = new BufferedReader(new InputStreamReader(p.getInputStream()));
                error = new BufferedReader(new InputStreamReader(p.getErrorStream()));
                String line;
                while ((line = in.readLine()) != null && flag) {
                    final String finalLine = line;
                    Log.e("pingCommand", flag+"");
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            tv_msg.setText(tv_msg.getText() + finalLine + "\n");
                            tv_msg.setSelection(tv_msg.getText().toString().length());
                        }
                    });
                }
                while ((line = error.readLine()) != null && flag) {
                    final String finalLine = line;
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            tv_msg.setText(tv_msg.getText() + finalLine + "\n");
                            tv_msg.setSelection(tv_msg.getText().toString().length());
                        }
                    });
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            } finally {
                try {
                    if (in != null) {
                        in.close();
                    }
                    if (error != null) {
                        error.close();
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    };


    private void initView() {
        et_host = findViewById(R.id.et_host);
        et_count = findViewById(R.id.et_count);
        et_timeout = findViewById(R.id.et_timeout);
        btn_ping = findViewById(R.id.btn_ping);
        btn_ping.setOnClickListener(this);
        tv_msg = findViewById(R.id.tv_msg);
        btn_help = findViewById(R.id.btn_help);
        btn_help.setOnClickListener(this);
        et_interval = findViewById(R.id.et_interval);
        mBtnStop = findViewById(R.id.btn_stop);
        mBtnStop.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            default:
                break;
            case R.id.btn_ping:
                flag = true;
                tv_msg.setText("");
                thread = new Thread(runnable);
                String threadName = thread.getName();
                Log.i("thread_log", String.format("线程启动了，名字为:%s", threadName));
                thread.start();
                break;
            case R.id.btn_help:
                String msg = "host    域名或者IP地址；\n"
                        + "timeout    以毫秒为单位设置ping的超时时间；\n"
                        + "count    ping指定次数后停止ping；\n"
                        + "interval    设定间隔几秒发送一个ping包，默认一秒ping一次；\n";
                AlertDialogUtil.alert(this, "帮助", msg, true);
                break;
            case R.id.btn_stop:
                flag = false;
                if (thread.isInterrupted()) {
                    Log.i("thread_log", "线程终止了");
                }
                break;
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        //得到菜单加载器对象
        MenuInflater menuInflater=getMenuInflater();
        //加载菜单文件
        menuInflater.inflate(R.menu.option_menu,menu);
        return super.onCreateOptionsMenu(menu);
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.ip_query:
                startActivity(new Intent(this, IPQueryActivity.class));
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * 双击退出函数
     */
    private static Boolean isExit = false;

    private void exitBy2Click() {
        Timer tExit;
        if (!isExit) {
            isExit = true; // 准备退出
            Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
            tExit = new Timer();
            tExit.schedule(new TimerTask() {
                @Override
                public void run() {
                    isExit = false; // 取消退出
                }
            }, 2000); // 如果2秒钟内没有按下返回键，则启动定时器取消掉刚才执行的任务
        } else {
            finish();
            System.exit(0);
        }
    }

    /**
     * 返回键响应
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exitBy2Click();
        }
        return false;
    }

}
